<?php
class Mageex_RelatedProduct_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
    	
    	$id = 166;
		
		$_product = Mage::getModel('catalog/product')->load($id);
		
		/*get child category*/
		$cate = $_product->getCategoryCollection();

		$visibility = array(
				Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
				Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
		);
		
		$_related = Mage::getModel('catalog/product')->getCollection()
			  ->addAttributeToSelect('*')
			  ->addAttributeToFilter('visibility', $visibility)
			  ->addAttributeToFilter('entity_id', array('nin' => array($id)))
			  ->addAttributeToSelect('small_image');
			  
		foreach($cate as $top){
			//add category to filter related collection
			$_related->addCategoryFilter($top);
		}
		
		//set random order for related collection
		$_related->getSelect()->order(new Zend_Db_Expr('RAND()'));
		
		//set limit product on relate;
		$_related->setPage(1, 7);
		
		
		/** get array of attribute code **/
		
		
		$arrCode = Mage::helper('relatedproduct/data')->getArrAttribute();	
		
		
		/******************************************/
		
		
		/** get array of filterable attribute code & value for current product**/
		/*
		$attributes = Mage::getModel('catalog/product');
		
		//Attribute code template product
		
		$attributeArray = array();
		
		foreach ($_product->getData() as $key=>$value){
			
			if(in_array($key, $arrCode)){
				 
				$actualValue = $attributes->getResource()
							->getAttribute($key)
							->getSource()
							->getOptionText($value);
				echo $actualValue ;
				if($actualValue!='No' && $actualValue !=NULL){
					$attributeArray[$key] = $value;
					//$_related->addAttributeToFilter($key, $value);
				}
			}
		}
		*/
		//echo count($_related);
		/*
		*	filter
		*/
		
		foreach($_related as $product){
			echo '<pre>';
			print_r($product->getName());
			echo '</pre>';
		}
		//var_dump();
		
		//echo $_related->getSelect()->__toString();
		
    }
}